<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="loading">
      <div slot="header" class="clearfix">
        <span>{{ exam.title }}</span>
        <div class="timer">
          <i class="el-icon-time"></i>
          <span>{{ formatTime(remainingTime) }}</span>
        </div>
      </div>
      
      <div v-if="exam && !loading">
        <!-- 考试信息 -->
        <div class="exam-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">学科：</span>
                <span>{{ exam.subjectName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">总分：</span>
                <span>{{ exam.totalScore }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">考试时长：</span>
                <span>{{ exam.duration }} 分钟</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 试卷导航 -->
        <div class="exam-nav">
          <div v-for="(section, sectionIndex) in sections" :key="'section-'+sectionIndex" class="section-nav">
            <div class="section-title" v-if="section.questions.length > 0">
              {{ section.name }}
            </div>
            <div class="question-nav-list">
              <el-button 
                v-for="(q, qIndex) in section.questions" 
                :key="'nav-'+sectionIndex+'-'+qIndex"
                size="mini"
                :type="isQuestionAnswered(q) ? 'success' : ''"
                @click="scrollToQuestion(sectionIndex, qIndex)">
                {{ sectionIndex + 1 }}-{{ qIndex + 1 }}
              </el-button>
            </div>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 试卷内容 -->
        <div class="exam-content">
          <div v-for="(section, sectionIndex) in sections" :key="sectionIndex" class="question-section">
            <h3 v-if="section.questions.length > 0" class="section-title">{{ section.name }}</h3>
            
            <div 
              v-for="(question, questionIndex) in section.questions" 
              :key="questionIndex" 
              class="question-item"
              :id="'question-'+sectionIndex+'-'+questionIndex">
              <div class="question-header">
                <div class="question-title">
                  <span class="question-index">{{ sectionIndex + 1 }}-{{ questionIndex + 1 }}.</span>
                  <span v-html="question.content"></span>
                  <span class="question-score">（{{ question.score }}分）</span>
                </div>
              </div>
              
              <!-- 选项（单选题） -->
              <div v-if="question.questionType === 1" class="question-options">
                <el-radio-group v-model="answers[question.id]">
                  <div v-for="(option, optionIndex) in parseOptions(question.options)" :key="optionIndex" class="option-item">
                    <el-radio :label="option.key">
                      <span class="option-key">{{ option.key }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
              
              <!-- 选项（多选题） -->
              <div v-if="question.questionType === 2" class="question-options">
                <el-checkbox-group v-model="answers[question.id]">
                  <div v-for="(option, optionIndex) in parseOptions(question.options)" :key="optionIndex" class="option-item">
                    <el-checkbox :label="option.key">
                      <span class="option-key">{{ option.key }}.</span>
                      <span class="option-content" v-html="option.content"></span>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              
              <!-- 判断题 -->
              <div v-if="question.questionType === 3" class="question-options">
                <el-radio-group v-model="answers[question.id]">
                  <el-radio label="true">正确</el-radio>
                  <el-radio label="false">错误</el-radio>
                </el-radio-group>
              </div>
              
              <!-- 填空题 -->
              <div v-if="question.questionType === 4" class="question-blanks">
                <div v-for="(blank, blankIndex) in getBlankCount(question)" :key="blankIndex" class="blank-item">
                  <span class="blank-label">空{{ blankIndex + 1 }}：</span>
                  <el-input 
                    v-model="getBlankAnswerArray(question.id)[blankIndex]" 
                    placeholder="请填写答案"
                    size="small"
                    class="blank-input">
                  </el-input>
                </div>
              </div>
              
              <!-- 简答题 -->
              <div v-if="question.questionType === 5" class="question-essay">
                <el-input 
                  type="textarea" 
                  v-model="answers[question.id]" 
                  :rows="4" 
                  placeholder="请输入答案">
                </el-input>
              </div>
            </div>
          </div>
        </div>
        
        <div class="submit-area">
          <el-button type="primary" @click="submitExam">提交试卷</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamDetail, submitExam } from '@/api/exam';

export default {
  name: 'StudentExamTake',
  data() {
    return {
      loading: false,
      submitting: false,
      exam: {
        id: null,
        title: '',
        description: '',
        totalScore: 0,
        duration: 0,
        subjectId: null,
        subjectName: '',
        educationLevel: null,
        educationLevelName: '',
        startTime: null,
        endTime: null,
        questions: []
      },
      sections: [
        { type: 1, name: '一、单选题', questions: [] },
        { type: 2, name: '二、多选题', questions: [] },
        { type: 3, name: '三、判断题', questions: [] },
        { type: 4, name: '四、填空题', questions: [] },
        { type: 5, name: '五、简答题', questions: [] }
      ],
      answers: {},
      remainingTime: 0,
      timer: null,
      examId: null
    };
  },
  created() {
    this.examId = this.$route.params.id;
    this.getExamDetail();
    
    // 监听页面关闭事件
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy() {
    this.clearTimer();
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  },
  methods: {
    // 获取考试详情
    getExamDetail() {
      this.loading = true;
      getExamDetail(this.examId, true).then(response => {
        this.exam = response.data;
        
        // 按题型分组
        this.sections.forEach(section => {
          section.questions = [];
        });
        
        if (this.exam.questions && this.exam.questions.length > 0) {
          this.exam.questions.forEach(question => {
            const section = this.sections.find(s => s.type === question.questionType);
            if (section) {
              section.questions.push(question);
            }
          });
        }
        
        // 初始化答案对象
        this.initAnswers();
        
        // 计算剩余时间
        this.remainingTime = this.exam.duration * 60;
        this.startTimer();
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取考试详情失败');
        this.$router.push('/student/exams');
      });
    },
    // 初始化答案对象
    initAnswers() {
      this.answers = {};
      this.exam.questions.forEach(question => {
        if (question.questionType === 2) {
          this.answers[question.id] = []; // 多选题初始化为空数组
        } else if (question.questionType === 4) {
          const blankCount = this.getBlankCount(question);
          this.answers[question.id] = new Array(blankCount).fill('');
        } else {
          this.answers[question.id] = ''; // 其他题型初始化为空字符串
        }
      });
    },
    // 启动计时器
    startTimer() {
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--;
        } else {
          this.clearTimer();
          this.submitExam(true);
        }
      }, 1000);
    },
    // 清除计时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    // 格式化时间
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0')
      ].join(':');
    },
    // 解析选项
    parseOptions(optionsStr) {
      if (!optionsStr) return [];
      
      try {
        return JSON.parse(optionsStr);
      } catch (e) {
        console.error('解析选项失败', e);
        return [];
      }
    },
    // 获取填空题的空格数量
    getBlankCount(question) {
      try {
        const blankAnswer = JSON.parse(question.answer);
        return blankAnswer.length;
      } catch (e) {
        return 1;
      }
    },
    // 获取填空题答案数组
    getBlankAnswerArray(questionId) {
      if (!this.answers[questionId] || !Array.isArray(this.answers[questionId])) {
        this.answers[questionId] = new Array(this.getBlankCount(
          this.exam.questions.find(q => q.id === questionId)
        )).fill('');
      }
      return this.answers[questionId];
    },
    // 判断题目是否已经作答
    isQuestionAnswered(question) {
      const answer = this.answers[question.id];
      
      if (question.questionType === 2) {
        // 多选题
        return Array.isArray(answer) && answer.length > 0;
      } else if (question.questionType === 4) {
        // 填空题
        return Array.isArray(answer) && answer.some(a => a.trim() !== '');
      } else {
        // 其他题型
        return answer && answer.trim() !== '';
      }
    },
    // 滚动到指定题目
    scrollToQuestion(sectionIndex, questionIndex) {
      const elementId = `question-${sectionIndex}-${questionIndex}`;
      const element = document.getElementById(elementId);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },
    // 处理页面关闭事件
    handleBeforeUnload(e) {
      e.preventDefault();
      e.returnValue = '考试尚未完成，确定要离开吗？';
    },
    // 提交试卷
    submitExam(isAutoSubmit = false) {
      if (this.submitting) return;
      
      if (!isAutoSubmit) {
        const message = `确定要提交试卷吗？剩余时间：${this.formatTime(this.remainingTime)}`;
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doSubmitExam();
        }).catch(() => {});
      } else {
        this.$alert('考试时间已结束，系统将自动提交您的试卷', '提示', {
          confirmButtonText: '确定',
          callback: () => {
            this.doSubmitExam();
          }
        });
      }
    },
    // 执行提交试卷
    doSubmitExam() {
      this.submitting = true;
      
      // 格式化答案数据
      const answerData = {
        examId: this.examId,
        answers: []
      };
      
      this.exam.questions.forEach(question => {
        let answerValue = this.answers[question.id];
        
        // 处理多选题答案
        if (question.questionType === 2 && Array.isArray(answerValue)) {
          answerValue = answerValue.join(',');
        }
        
        // 处理填空题答案
        if (question.questionType === 4 && Array.isArray(answerValue)) {
          answerValue = JSON.stringify(answerValue);
        }
        
        answerData.answers.push({
          questionId: question.id,
          answer: answerValue || '',
          questionType: question.questionType
        });
      });
      
      submitExam(answerData).then(response => {
        this.submitting = false;
        this.clearTimer();
        
        this.$alert('试卷提交成功！', '提示', {
          confirmButtonText: '确定',
          callback: () => {
            this.$router.push(`/student/exam/result/${response.data}`);
          }
        });
      }).catch(() => {
        this.submitting = false;
        this.$message.error('提交失败，请重试');
      });
    }
  }
};
</script>

<style scoped>
.timer {
  float: right;
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.exam-info {
  margin-bottom: 20px;
}

.info-item {
  line-height: 24px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.exam-nav {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.section-nav {
  margin-right: 20px;
  margin-bottom: 10px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.question-nav-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.question-section {
  margin-bottom: 30px;
}

.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  margin-bottom: 15px;
}

.question-title {
  line-height: 1.6;
}

.question-index {
  font-weight: bold;
  margin-right: 5px;
}

.question-score {
  font-size: 14px;
  color: #409EFF;
  margin-left: 10px;
}

.question-options {
  margin-left: 20px;
}

.option-item {
  margin-bottom: 10px;
}

.option-key {
  font-weight: bold;
  margin-right: 10px;
}

.question-blanks {
  margin-left: 20px;
}

.blank-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.blank-label {
  margin-right: 10px;
  font-weight: bold;
  min-width: 60px;
}

.blank-input {
  width: 300px;
}

.question-essay {
  margin-left: 20px;
}

.submit-area {
  margin-top: 30px;
  text-align: center;
}
</style> 